using System;

namespace org.paulbanks.BarcodeDotNet.Encoders
{
	/// <summary>
	/// Encoder for CODE128 A and B
	/// </summary>
	public class Code128_AB : Code128 {
	
		private int StartCode;

		public Code128_AB() {			
			StartCode = START_B;            
		}

		public enum ABType {
			A,
			B
		}

		public Code128_AB(ABType type) {

			switch (type) {
				case ABType.A:
					StartCode = START_A;
					break;
				case ABType.B:
					StartCode = START_B;
					break;
			}

		}

		override public bool Verify(string strText) {

			if (strText=="") return false;
			char[] a = strText.ToCharArray();
            
			for (int i=0;i<strText.Length;i++)
				if (a[i]<32 || (a[i]&0x80)!=0) return false;				

			return true;			

		}

		override public string Encode(string strText) {
            
			if (!Verify(strText)) throw new Exception("Invalid");
            
			string strEnc = "0"; // First space
			strEnc += codeset[StartCode];
			int checksum = 0;
			checksum += StartCode;

			char[] a = strText.ToCharArray();
			for (int i=0;i<strText.Length;i++) 
			{
				int code = a[i] - 32;
				strEnc += codeset[code];
				checksum += code * (i+1);
			}

			// Add checksum and end marker
			checksum %= 103;
			strEnc += codeset[checksum];
			strEnc += codeset[STOP];

			return strEnc;
            
		}

	}
}
